// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <pollux/functions/prestosql/json/simd_json_wrapper.h>

#include <melon/preprocessor.h>

#define SIMDJSON_ASSIGN_OR_RAISE_IMPL(_resultName, _lhs, _rexpr) \
  auto&& _resultName = (_rexpr);                                 \
  if (_resultName.error() != ::simdjson::SUCCESS) {              \
    return _resultName.error();                                  \
  }                                                              \
  _lhs = std::move(_resultName).value_unsafe();

/// Helper to extract simdjson_result<T>.  Return immediately if the result is
/// an error.  Examples:
///
///   std::string s;
///   SIMDJSON_ASSIGN_OR_RAISE(s, simdjson::to_json_string(v));
///
///   SIMDJSON_ASSIGN_OR_RAISE(auto s, simdjson::to_json_string(v));
#define SIMDJSON_ASSIGN_OR_RAISE(_lhs, _rexpr) \
  SIMDJSON_ASSIGN_OR_RAISE_IMPL(               \
      FB_ANONYMOUS_VARIABLE(_simdjsonResult), _lhs, _rexpr)

namespace kumo::pollux {
    /// Initialize the exceptions array with all possible simdjson error codes.
    void simdjsonErrorsToExceptions(
        std::exception_ptr exceptions[simdjson::NUM_ERROR_CODES]);

    /// Parse the input json string using a thread local on demand parser.
    simdjson::simdjson_result<simdjson::ondemand::document> simdjsonParse(
        const simdjson::padded_string_view &json);

    /// Returns a simdjson::padded_string_view object from the input
    /// std::string_view object to avoid creating a new copy of the
    /// std::string_view. NOTE: The user MUST ensure that the input 'json' already
    /// has simdjson::SIMDJSON_PADDING at the end.
    simdjson::padded_string_view reusePaddedStringView(
        const std::string_view &json);
} // namespace kumo::pollux
